/**
 * Created by JetBrains WebStorm.
 * User: mumble
 * Date: 3/11/12
 * Time: 12:55 AM
 * To change this template use File | Settings | File Templates.
 */

function WsClient()
{
    this.url = "";
    this.conn = null;
    this.game = null;
    this.lobbyClient = null;
    this.isConnected = false;

}

WsClient.prototype = {
    lobbyClient: null,
    setGame : function(game)
    {
        this.game = game;
    },
    connect : function(url, port)
    {
        this.url = "ws://"+url+":"+port;
        this.conn = new WebSocket(this.url);
        this.conn.parent = this;
        this.conn.onopen = this.onOpen;
        this.conn.onclose = this.onClose;
        this.conn.onmessage= this.onMessage;
    },
    onOpen : function(event)
    {
        console.log('Ket noi thanh cong');
        this.parent.lobbyClient = new LobbyClient(this.parent);
        this.parent.isConnected = true;
    },
    onClose : function(event)
    {
        if(this.parent.game != null)
            this.parent.game.onDisconnect(event);
        this.parent.isConnected = false;
    },
    onMessage : function(event)
    {
        var package = null;
        try
        {
            package = JSON.parse(event.data);
        }
        catch(e)
        {
            return;
        }
        switch(package[0])
        {
            case PING_PACKAGE:
                break;
            case GAME_PACKAGE:
                if(this.game != null)
                    this.parent.game.onGamePackage(package[1]);
                break;
            case CONTROL_PACKAGE:
                if(this.parent.lobbyClient != null)
                    this.parent.lobbyClient.onControlPackage(package[1]);
                break;
        }


    },
    postGameMessage : function(msg)
    {
        var package = JSON.stringify([GAME_PACKAGE, msg]);
        this.conn.send(msg);



    },
    postControlMessage : function(msg)
    {
        var package = JSON.stringify([CONTROL_PACKAGE, msg]);
        this.conn.send(package);
    }

};

